﻿using System;
using RK.Common;
using RK.Common.GraphicsEngine.Core;
using RK.Store.MetroSnake.UI;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227

namespace RK.Store.MetroSnake
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();

            this.Suspending += OnSuspending;
            this.UnhandledException += OnUnhandledException;

            CommonUtil.UnhandledException += OnCommonUtilUnhandledException;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            //Initialize the graphics engine
            Exception graphicsException = null;
            try
            {
                GraphicsCore.Initialize(TargetHardware.DirectX11, false);
            }
            catch (Exception ex)
            {
                graphicsException = ex;
            }

            //Create and show mainpage on the window
            FrameworkElement mainPage = null;
            if (graphicsException == null)
            {
                mainPage = new MainPage();
            }
            else
            {
                mainPage = new ExceptionPage();
                mainPage.DataContext = graphicsException;
            }

            //Start main window logic
            Window.Current.Content = mainPage;
            mainPage.InvokeDelayed(
                () => Window.Current.Activate(),
                TimeSpan.FromMilliseconds(100.0));
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            deferral.Complete();
        }

        /// <summary>
        /// Logic to be invoked on unhandled exceptions.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="UnhandledExceptionEventArgs" /> instance containing the event data.</param>
        private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            ExceptionPage exceptionPage = new ExceptionPage();
            exceptionPage.DataContext = e.Exception;
            Window.Current.Content = exceptionPage;
        }

        private async void OnCommonUtilUnhandledException(object sender, UnhandledExceptionArgs e)
        {
            await Window.Current.Dispatcher.RunAsync(
                Windows.UI.Core.CoreDispatcherPriority.High,
                () =>
                {
                    ExceptionPage exceptionPage = new ExceptionPage();
                    exceptionPage.DataContext = e.Exception;
                    Window.Current.Content = exceptionPage;
                });
        }
    }
}